package com.zhanggm.s3.house.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.zhanggm.s3.house.entity.HouseAnjuke;
import com.zhanggm.s3.house.mapper.HouseAnjukeMapper;
import com.zhanggm.s3.house.service.IHouseAnjukeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 * https://blog.csdn.net/MariaOzawa/article/details/115603713
 * @author zhanggm
 * @since 2023-07-28
 */
@Service
@Slf4j
@DS("2103a-house")
public class HouseAnjukeServiceImpl extends ServiceImpl<HouseAnjukeMapper, HouseAnjuke> implements IHouseAnjukeService {

    private Map<String, Long> localCache = new HashMap<>();

    @Override
    public PageInfo getPageInfo(HouseAnjuke house, Integer pageNum, Integer pageSize) {
        //计算总页数
        StringBuffer sb = new StringBuffer("cacheKey");
        QueryWrapper<HouseAnjuke> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(house.getTitle())) {
            queryWrapper.likeRight("title",house.getTitle());
            sb.append(house.getTitle());
        }
        if (!StringUtils.isEmpty(house.getDetailItem())) {
            queryWrapper.likeRight("detail_item", house.getDetailItem());
            sb.append(house.getDetailItem());
        }
        //本地缓存
        String cacheKey = DigestUtil.md5Hex(sb.toString());
        Long totalRecord = localCache.get(cacheKey);
        if (totalRecord == null) {
            totalRecord = this.count(queryWrapper);
            localCache.put(cacheKey, totalRecord);
        }
        //计算分页信息
        Long totalPage = (totalRecord  +  pageSize  - 1) / pageSize;
        long offset = (pageNum - 1) * pageSize;
        //查询数据
        List<HouseAnjuke> list = getBaseMapper().getPageInfo(house, offset, pageSize);
        //封装分页
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setPageNum(pageNum);
        pageInfo.setTotal(totalRecord);
        pageInfo.setPages(totalPage.intValue());
        pageInfo.setPageSize(pageSize);
        return pageInfo;
    }
}
